package com.lihepeng.leecode.juc;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 资源类
 */
class Foo{
    private ReentrantLock lock = new ReentrantLock();
    private  int state = 1;
    Condition condition1= lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();
    public void print01() throws InterruptedException {
        lock.lock();
        try {
            while (state !=1){
                condition1.await();
            }
            // 干活
            System.out.println("First");
            state =2;
            condition2.signalAll();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
    public void print02() throws InterruptedException {
        lock.lock();
        try {
            while (state !=2){
                condition2.await();
            }
            System.out.println("Second");
            state =3;
            condition3.signalAll();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
    public void print03() throws InterruptedException {
        lock.lock();
        try {
            while (state !=3){
                condition3.await();
            }
            System.out.println("Third");
            state =1;
            condition1.signalAll();
        }finally {
            lock.unlock();
        }

    }
}
/**
 * 打印demo 3
 *
 */
public class PrintDemo3 {
    public static void main(String[] args) {
        Foo foo = new Foo();
        new Thread(()->{
            for (int i=0;i<1000;i++) {
                try {
                    foo.print01();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"t1").start();
        new Thread(()->{
            for (int i=0;i<1000;i++) {
                try {
                    foo.print02();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"t2").start();
        new Thread(()->{
            for (int i=0;i<1000;i++) {
                try {
                    foo.print03();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"t3").start();

    }
}
